package com.ruiyangwang.ListenBook.servlet.track;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruiyangwang.ListenBook.repository.TrackRepo;
import com.ruiyangwang.ListenBook.util.Log;
import com.ruiyangwang.ListenBook.viewObject.UserV0;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.HashMap;

/**
 * @author syzygy
 * @date 2022/07/20 11:16
 **/
@WebServlet("/studio/track/record.json")
public class RecordJsonServlet extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final TrackRepo trackRepo = new TrackRepo();
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String title = req.getParameter("title");
        String type = req.getHeader("Content-Type");
        type = type.substring(0,type.indexOf(";"));
        Log.println("title：" + title);
        Log.println("type:" + type);
        //完整的音频放在这
        ServletInputStream inputStream = req.getInputStream();
        //保存到本地文件中
//        try(OutputStream os = new FileOutputStream("D:\\upload\\" + title + ".ogg")){
//            byte[] buf = new byte[1024];
//            while(true){
//                int n = inputStream.read(buf);
//                if(n == -1){
//                    break;
//                }
//                os.write(buf,0,n);
//            }
//            os.flush();
//        }
        UserV0 currentUser = null;
        HttpSession session = req.getSession(false);
        if(session != null){
            currentUser = (UserV0) session.getAttribute("currentUser");
        }
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        if(currentUser == null){
            Log.println("用户未登录");
            HashMap<String,Boolean> result = new HashMap<>();
            result.put("result",false);
            String json = objectMapper.writeValueAsString(result);
            Log.println(json);
            writer.println(json);
            return;
        }

        trackRepo.insert(currentUser.uid,title,type,req.getInputStream());
        HashMap<String,Boolean> result = new HashMap<>();
        result.put("result",true);
        String json = objectMapper.writeValueAsString(result);
        Log.println(json);
        writer.println(json);
    }
}